package com.algo.pattern.observable.inventory;

import com.algo.pattern.observable.constant.OperationTypeConstant;
import com.algo.pattern.observable.model.OrderInfo;
import com.algo.pattern.observable.model.StockUpdateMessage;
import com.algo.pattern.observable.observable.StockUpdateObserverManager;
import com.algo.pattern.observable.queue.StockUpdateQueueManager;
import com.algo.pattern.observable.queue.StockUpdateQueueManagerImpl;

import java.util.UUID;

public class StockServiceImpl implements StockService {

    private StockUpdateQueueManager queueManager = StockUpdateQueueManagerImpl.getInstance();

    private StockUpdateObserverManager observerManager = StockUpdateObserverManager.getInstance();

    /**
     * 库存出库，订单中心下单后，会调用过来扣减商品库存
     * @param orderInfo
     */
    @Override
    public void stockOut(OrderInfo orderInfo) {
        System.out.println("下单成功，开始更新库存中心本地数据");
        // 根据订单信息扣减相应商品库存
        // .... 更新数据库
        System.out.println("更新库存中心本地数据成功");

        StockUpdateMessage stockUpdateMessage = new StockUpdateMessage();
        stockUpdateMessage.setMessageId(UUID.randomUUID().toString());
        stockUpdateMessage.setOperationType(OperationTypeConstant.ORDER_CREATE);
        stockUpdateMessage.setOrderInfo(orderInfo);
        // 将库存更新的操作添加到内部队列中，调度中心那边从队列中拿消息来消费
        queueManager.put(stockUpdateMessage);

        // 监听处理结果
        observerManager.observer(stockUpdateMessage.getMessageId());
    }

}
